<?php

namespace App\Console\Commands;

use App\Http\Models\UserAmountLog;
use App\Http\Models\ZtkTask;
use App\Http\Models\ZtkUser;
use App\Http\Models\Order;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\QueryException;

class syncTaokeyi extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'syncTaokeyi';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '淘客易';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        DB::table('ztk_test')->insert([
            'remark' => '同步淘客易',
            'content' => '111',
            'created_at' => date('Y-m-d H:i:s',time())
        ]);
        $page = 1;
        $limit = 10000;
        $results = Order::whereHas('task',function($query){
            return $query->whereIn('status',[1,3]);
        })->with('user')->where('status',1)->where('taokeyi_at',NULL)->paginate($limit, ['*'], 'page', $page);

        $taokeyiList = [];
        foreach ($results->items() as $item){

            $tkyinfo = $this->getTkyInfo($item->task->goods_id,$taokeyiList);
            if(!$tkyinfo) continue;

            foreach($tkyinfo as $k=>$v)
            {
                if($v['gname'] != $item->user->union_name) continue;

                DB::beginTransaction();
                try {
                    $user = ZtkUser::where('union_name',$v['gname'])->where('id',$item->user_id)->first();
                    if(!$user) continue;

                    $amount = $item->type == 1 ? $item->price : $item->offer_price; //任务佣金

                    Order::where('id',$item->id)->update([
                        'status' => 2,
                        'finish_at' => date('Y-m-d H:i:s',time()),
                        'taokeyi_at' => date( "Y-m-d H:i:s", $v['sendtime'])
                    ]);

                    ZtkTask::where('id',$item->task->id)->where('goods_id',$item->task->goods_id)->where('user_id',$item->publish_user_id)->whereIn('status',[1,3])->increment('finish_num',1);

                    $user->increment('amount',$amount);

                    UserAmountLog::create([
                        'user_id'  => $user->id,
                        'trade_no' => get_order_no($user->id),
                        'amount'   => $amount,
                        'after_amount' => $user->amount,
                        'type'     => 1,
                        'class'    => 6,
                    ]);

                    DB::commit();
                    
                    break;
                } catch (QueryException $e) {
                    DB::rollBack();
                    break;
                }
            }
        }
    }

    public function getTkyInfo($itemid='',&$taokeyiList=[])
    {
        if(isset($taokeyiList[$itemid])){
            return $taokeyiList[$itemid];
        }
        $day = strtotime(date('Y-m-d',strtotime('+1 day')));
        $url = 'http://zsqapp.hz.taeapp.com/tkyinfo.php?itemid='.$itemid.'&start='.$day;
        $res = $this->curl_file_get_contents($url);
        $res = json_decode($res,1);

        // $tkyinfo = '[
        //     {
        //         "gname": "飞哥战队",
        //         "sendtime": 1578566510
        //     },
        //     {
        //         "gname": "淘达人",
        //         "sendtime": 1578530719
        //     },
        //     {
        //         "gname": "起凡精选",
        //         "sendtime": 1578530289
        //     }
        // ]';
        // $tkyinfo = json_decode($tkyinfo,1);

        if(!empty($res) && is_array($res)){
            return $taokeyiList[$itemid] = $res;
        }else{
            return false;
        }
    }

    function curl_file_get_contents($durl)
    {
        $headers = array(
        );
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $durl);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true) ;
        curl_setopt($curl, CURLOPT_BINARYTRANSFER, true) ;
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLINFO_HEADER_OUT, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        $data = curl_exec($curl);
        curl_close($curl);

        return $data;
    }

    

}
